﻿using Kalman;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace QuDao
{
    /// <summary>
    /// 高德地图API调用工具类
    /// </summary>
    public class AmapUtil
    {
        const string key = "e9faff7fdc6e1e1e4eebb13be1100e0d";//巴南高德账号KEY（17516515@qq.com）

        /// <summary>
        /// 根据经纬度获取地址
        /// </summary>
        /// <param name="s">经度纬度组成的字符串 例如:"113.692100,34.752853"</param>
        /// <param name="timeout">超时时间默认10秒</param>
        /// <returns>失败返回"" </returns>
        public static JObject GetLocation(string s, int timeout = 10000)
        {
            string url = $"http://restapi.amap.com/v3/geocode/regeo?key={key}&location={s}";
            return ApiCall(url, timeout);
        }

        /// <summary>
        /// 根据经纬度获取地址
        /// </summary>
        /// <param name="lng">经度 例如:113.692100</param>
        /// <param name="lat">维度 例如:34.752853</param>
        /// <param name="timeout">超时时间默认10秒</param>
        /// <returns>失败返回"" </returns>
        public static JObject GetLocation(decimal lng, decimal lat, int timeout = 10000)
        {
            string url = $"http://restapi.amap.com/v3/geocode/regeo?key={key}&location={lng},{lat}";
            return ApiCall(url, timeout);
        }

        /// <summary>
        /// 根据经纬度获取区县ID（国标码）
        /// </summary>
        /// <param name="lng">经度 例如:113.692100</param>
        /// <param name="lat">维度 例如:34.752853</param>
        /// <param name="timeout">超时时间默认10秒</param>
        /// <returns></returns>
        public static int GetDistrictID(decimal lng, decimal lat, int timeout = 10000)
        {
            if (lng == decimal.Zero && lat == decimal.Zero) return 0;
            var jo = GetLocation(lng, lat, timeout);
            var id = jo["regeocode"]["addressComponent"]["adcode"].ToObject<int>();
            return id;
        }

        /// <summary>
        /// 根据URL获取地址
        /// </summary>
        /// <param name="url">Get方法的URL</param>
        /// <param name="timeout">超时时间默认10秒</param>
        /// <returns></returns>
        private static JObject ApiCall(string url, int timeout = 10000)
        {
            try
            {
                var req = WebRequest.Create(url) as HttpWebRequest;
                req.ContentType = "multipart/form-data";
                req.Accept = "*/*";
                //req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
                req.UserAgent = "";
                req.Timeout = timeout;
                req.Method = "GET";
                req.KeepAlive = true;

                var result = "";
                var response = req.GetResponse() as HttpWebResponse;
                using (var sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    result = sr.ReadToEnd();
                }

                var jo = JObject.Parse(result);
                if(jo["status"].ToObject<int>() != 1)
                {
                    throw new Exception($"{jo["infocode"]}-{jo["info"]}");
                }
                return jo;
            }
            catch (Exception ex)
            {
                throw new AppException("高德API调用失败", ex);
            }
        }
    }
}
